'use strict';

const Controller = require('egg').Controller;

class field extends Controller {
  // 加字段
  async add() {
    const { ctx, service, app } = this;
    const body = ctx.request.merge({
      table_id: null,
      name: '',
      index: 0,
      is_search: 1,
      must_search: 0,
      show_search: 1,
    }, ctx.request.body);

    const valid = app.checkAND([
      { value: body.table_id, type: 'int' },
      body.name,
    ]);
    if (!valid) {
      ctx.body = ctx.response.errResult(4001);
      return;
    }

    const data = await service.field.add(...Object.values(body));
    if (!data) {
      ctx.body = ctx.response.errResult(4002);
      return;
    }
    ctx.body = ctx.response.successResult(2001);
  }

  // 加字段 批量加
  async addmost() {
    const { ctx, service, app } = this;
    const body = ctx.request.merge({
      table_id: null,
      fields: [],
    }, ctx.request.body);
    const valid = app.checkAND([
      { value: body.table_id, type: 'int' },
      { value: body.fields, type: 'hasArray' },
    ]);
    if (!valid) {
      ctx.body = ctx.response.errResult(4001);
      return;
    }

    const data = await service.field.addmost(body.table_id, body.fields);
    if (!data) {
      ctx.body = ctx.response.errResult(4002);
      return;
    }
    ctx.body = ctx.response.successResult(2001);
  }

  // 查字段
  async query() {
    const { ctx, service, app } = this;
    const body = ctx.request.merge({
      table_id: null,
    }, ctx.request.body);

    const valid = app.checkAND([
      { value: body.table_id, type: 'int' },
    ]);
    if (!valid) {
      ctx.body = ctx.response.errResult(4001);
      return;
    }

    const data = await service.field.query(body.table_id);
    ctx.body = ctx.response.successResult(2001, data);
  }

  // 更新字段
  async update() {
    const { ctx, service, app } = this;
    const body = ctx.request.merge({
      id: null,
      name: '',
      type:'文本',
      index: null,
      is_search: null,
      must_search: null,
      show_search: null,
    }, ctx.request.body);

    const valid = app.checkAND([
      { value: body.id, type: 'int' },
    ]);
    if (!valid) {
      ctx.body = ctx.response.errResult(4001);
      return;
    }
    const data = await service.field.update(...Object.values(body));
    if (!data) {
      ctx.body = ctx.response.errResult(4002);
      return;
    }
    ctx.body = ctx.response.successResult(2001);
  }

  /**
   * 删除表字段
   */
  async delete() {
    const { ctx, service, app } = this;
    const body = ctx.request.merge({
      ids: [],
    }, ctx.request.body);

    const valid = app.checkAND([
      { value: body.ids, type: 'hasArray' },
    ]);
    if (!valid) {
      ctx.body = ctx.response.errResult(4001);
      return;
    }
    await service.field.delete(body.ids);
    ctx.body = ctx.response.successResult(2001);
  }
}

module.exports = field;
